package cn.xhjava.crm.settings.controller;

import cn.xhjava.crm.commons.ReturnObject;
import cn.xhjava.crm.commons.SysContants;
import cn.xhjava.crm.commons.util.DateUtils;
import cn.xhjava.crm.commons.util.ExceptionUtil;
import cn.xhjava.crm.settings.domain.User;
import cn.xhjava.crm.settings.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Author:   XiaHu
 * Date:     2023/6/20
 * 用户视图
 */
@Controller
public class UserContoller {
    private static final Logger log = LoggerFactory.getLogger(UserContoller.class);

    @Autowired
    private UserService userService;

    /**
     * url要和controller方法处理完请求之后，响应信息返回的页面的资源目录保持一致
     * 访问首页时,通过拦截器,直接跳转到登陆界面
     */
    @RequestMapping("/settings/xiahu/user/toLogin")
    public String toLogin() {
        //请求转发到登录页面
        return "settings/xiahu/user/login";
    }


    @RequestMapping("/settings/xiahu/user/toRegister")
    public String toRegister() {
        //请求转发到登录页面
        return "settings/xiahu/user/register";
    }

    @PostMapping("/settings/xiahu/user/login")
    public @ResponseBody
    Object login(String loginAct, String loginPwd, String isRemPwd, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        //封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("loginAct", loginAct);
        map.put("loginPwd", loginPwd);
        //调用service层方法，查询用户
        User user = null;
        try {
            user = userService.queryUserByLoginActAndPwd(map);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }

        //根据查询结果，生成响应信息
        ReturnObject returnObject = new ReturnObject();
        if (user == null) {
            //登录失败,用户名或者密码错误
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("用户名或者密码错误");
        } else {//进一步判断账号是否合法
            if (DateUtils.formateDateTime(new Date()).compareTo(user.getExpireTime()) > 0) {
                //登录失败，账号已过期
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("账号已过期");
            } else if ("0".equals(user.getLockState())) {
                //登录失败，状态被锁定
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("状态被锁定");
            } else {
                log.info("{} login success", loginAct);
                //登录成功
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);

                //把user保存到session中
                session.setAttribute(SysContants.SESSION_USER, user);

                //如果需要记住密码，则往外写cookie
                if ("true".equals(isRemPwd)) {
                    Cookie c1 = new Cookie("loginAct", user.getLoginAct());
                    c1.setMaxAge(10 * 24 * 60 * 60);
                    response.addCookie(c1);
                    Cookie c2 = new Cookie("loginPwd", user.getLoginPwd());
                    c2.setMaxAge(10 * 24 * 60 * 60);
                    response.addCookie(c2);
                } else {
                    //把没有过期cookie删除
                    Cookie c1 = new Cookie("loginAct", "1");
                    c1.setMaxAge(0);
                    response.addCookie(c1);
                    Cookie c2 = new Cookie("loginPwd", "1");
                    c2.setMaxAge(0);
                    response.addCookie(c2);
                }
            }
        }
        // 返回登陆状态,前端jsp页面根据返回状态进行后续逻辑处理
        // 如果返回状态 = 1 ,表示登陆成功、跳转到 workbench/index.do
        // 否则、打印登陆信息
        return returnObject;
    }


    @PostMapping("/settings/xiahu/user/register")
    public @ResponseBody
    Object register(String loginAct, String username, String loginPwd, String email) {
        //封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("loginAct", loginAct);
        map.put("username", username);
        map.put("loginPwd", loginPwd);
        map.put("email", email);
        //调用service层方法，查询用户
        User user = null;
        try {
            user = userService.queryUserByLoginAct(map);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }

        //根据查询结果，生成响应信息
        ReturnObject returnObject = new ReturnObject();
        if (user != null) {
            //登录失败,用户名或者密码错误
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("用户已经存在");
            return returnObject;
        }
        try {
            userService.add(map);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        //注册成功
        returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
        returnObject.setMessage("注册成功");


        return returnObject;
    }


    @RequestMapping("/settings/xiahu/user/logout")
    public String logout() {
        log.info("退出登陆");

        // 跳转到登陆页面
        return "settings/xiahu/user/login";
    }


    @PostMapping("/settings/xiahu/user/update")
    public @ResponseBody
    Object update(String oldPwd, String newPwd, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        ReturnObject returnObject = new ReturnObject();
        if (user == null) {
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setMessage("老密码有误,修改密码失败");
            return returnObject;
        }


        if (!oldPwd.equals(user.getLoginPwd())) {
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setMessage("老密码有误,修改密码失败");
            return returnObject;
        }

        user.setLoginPwd(newPwd);

        int success = 0;
        try {
            success = userService.update(user);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        if (success == 1) {
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setMessage("密码修改成功");
        } else {
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("修改密码失败");
        }
        return returnObject;
    }

    @PostMapping("/settings/xiahu/user/myInformation")
    public @ResponseBody
    Object queryMyInformation(HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        return user;
    }
}